<template>
  <div class="app-container">
    <el-form :inline="true" :model="getFormDate" class="demo-form-inline">
      <el-form-item>
        <el-input size="mini" v-model="getFormDate.username" placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input size="mini" v-model="getFormDate.nickName" placeholder="请输入昵称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-select size="mini" v-model="getFormDate.gender" clearable placeholder="请选择性别">
          <el-option v-for="item in genders" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getUsers" size="mini">查询</el-button>
      </el-form-item>
    </el-form>
    <el-button style="margin-bottom: 5px;" size="mini" @click="add">新增</el-button>
    <el-button style="margin-bottom: 5px;" size="mini" @click="handlerBatchDelete">批量删除</el-button>
    <el-table size="mini" :data="tableData" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="setRoles(scope.$index, scope.row)">角色设置</el-button>
          <el-button size="mini" type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="账号">
      </el-table-column>
      <el-table-column prop="avatar" label="头像">
        <template slot-scope="scope">
          <el-image style="width: 70px; height: 70px" :src="scope.row.avatarPath" :preview-src-list="[scope.row.avatarPath]"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="nickName" label="昵称">
      </el-table-column>
      <el-table-column prop="gender" label="性别">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.gender == 1">男</el-tag>
          <el-tag type="success" v-else>女</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="mobile" label="电话">
      </el-table-column>
      <el-table-column prop="email" label="邮箱">
      </el-table-column>
      <el-table-column prop="roles" label="角色">
        <template slot-scope="scope">
          <div v-for="role in scope.row.roles">
            <el-tag size="mini" type="success">{{ role.name }}</el-tag>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="float: right;margin-top: 5px;" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="pageSize"
      layout="prev, pager, next, jumper" :total="totalNum">
    </el-pagination>
    <el-dialog title="添加用户" :visible.sync="dialogVisibleAdd" width="30%">
      <el-form :model="addFormData" label-width="80px" ref="addFormData">
        <el-form-item label="头像">
          <el-upload class="avatar-uploader" :action="uploadAction" :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="addFormData.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="addFormData.password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="addFormData.nickName" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="addFormData.gender" placeholder="请选择性别">
            <el-option v-for="item in genders" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="addFormData.mobile" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="addFormData.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="createUser">确认</el-button>
          <el-button @click="resetFormAdd('addFormData')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="修改用户" :visible.sync="dialogVisibleUpdate" width="30%">
      <el-form :model="updateFormData" label-width="80px">
        <el-form-item label="头像">
          <el-upload class="avatar-uploader" :action="uploadAction" :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="updateFormData.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <!-- <el-form-item label="密码">
          <el-input v-model="updateFormData.password" placeholder="请输入密码" show-password></el-input>
        </el-form-item> -->
        <el-form-item label="昵称">
          <el-input v-model="updateFormData.nickName" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="updateFormData.gender" placeholder="请选择性别">
            <el-option v-for="item in genders" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="updateFormData.mobile" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="updateFormData.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="updateUser">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="角色设置" :visible.sync="dialogVisibleSetRole" width="30%">
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;"></div>
      <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRolesChange">
        <el-checkbox v-for="role in rolesOptions" :label="role.id" :key="role.id">{{ role.name }}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="setRolesOk">确 定</el-button>
        <el-button size="mini" @click="dialogVisibleSetRole = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserByPage, addUser, deleteUser, getUserById, updateUserById, batchDeleteUser, geRoleByPage, setRoles } from "@/api/system.js"
export default {
  data() {
    return {
      list: null,
      listLoading: true,
      getFormDate: {},
      roleIds: [],
      tableData: [],
      multipleSelection: [],
      formInline: {
        user: '',
        region: ''
      },
      genders: [
        { value: "1", label: "男" },
        { value: "0", label: "女" },
      ],
      ids: [],
      rolesOptions: [],
      dialogVisibleAdd: false,
      dialogVisibleUpdate: false,
      dialogVisibleSetRole: false,
      updateFormData: {},
      addFormData: {
        username: '',
        password: '',
        nickName: '',
        gender: '',
        mobile: '',
        email: ''
      },
      pageSize: 10,
      currentPage: 1,
      totalNum: 0,
      checkAll: false,
      checkedRoles: [],
      isIndeterminate: true,
      updateId: '',
      uploadAction: "/api/upload",
      imageUrl: '',
      uploadId: ''
    }
  },
  created() {
    this.initRolesOptions();
    this.initTableData()
  },
  methods: {
    initRolesOptions() {
      let senddata = {
        size: 100,
        page: this.currentPage
      }
      geRoleByPage(senddata).then(res => {
        if (res.data.code == 200) {
          this.roleIds = res.data.data.records.map(item => {
            return item.id
          })
          this.rolesOptions = res.data.data.records
        }
      })
    },
    setRoles(index, row) {
      this.checkedRoles = []
      if (row.roles) {
        this.checkedRoles = row.roles.map(item => {
          return item.id
        })
      }
      this.dialogVisibleSetRole = true
      this.updateId = row.id
    },
    resetFormAdd(formName) {
      this.addFormData = {}
      this.$refs[formName].resetFields();
    },
    handleAvatarSuccess(res, file) {
      // this.uploadId = res.data.id
      this.addFormData.avatarPath = res.data
      this.updateFormData.avatarPath = res.data
      this.imageUrl = res.data
      // this.imageUrl = URL.createObjectURL(file.raw);
      console.log("this.imageUrl", this.imageUrl);
    },
    createUser() {
      let senddata = {
        ...this.addFormData
        // avatar: this.uploadId
      }
      addUser(senddata).then(res => {
        if (res.data.code == 200) {
          this.$message.success("添加成功")
          this.dialogVisibleAdd = false
          this.initTableData();
        }
      })
    },
    updateUser() {
      let senddata = {
        ...this.updateFormData
        // avatar: this.uploadId
      }
      updateUserById(senddata).then(res => {
        if (res.data.code == 200) {
          this.$message.success("修改成功")
          this.dialogVisibleUpdate = false
          this.initTableData();
        }
      })
    },
    handlerBatchDelete() {
      if (this.multipleSelection.length > 0) {
        this.ids = this.multipleSelection.map(item => {
          return item.id
        })
        batchDeleteUser(this.ids).then(res => {
          if (res.data.code == 200) {
            this.$message.success("批量删除成功")
            this.initTableData()
          }
        })
      } else {
        this.$message.warning("请先选择删除项")
      }
    },
    initTableData(page) {
      let senddata = {
        ...this.getFormDate,
        size: this.pageSize,
        page: page ? page : this.currentPage
      }
      getUserByPage(senddata).then(res => {
        if (res.data.code == 200) {
          this.tableData = res.data.data.records
          this.totalNum = res.data.data.total
        }
      })
    },
    add() {
      this.addFormData = {}
      this.imageUrl = ''
      this.dialogVisibleAdd = true
    },
    handleEdit(index, row) {
      this.dialogVisibleUpdate = true
      getUserById(row.id).then(res => {
        if (res.data.code == 200) {
          this.updateFormData = res.data.data
          this.imageUrl = res.data.data.file.path
        }
      })
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(row.id).then(res => {
          if (res.data.code == 200) {
            this.$message.success("删除成功")
            this.initTableData();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getUsers() {
      this.initTableData();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.initTableData(val)
    },
    handleCheckAllChange(val) {
      this.checkedRoles = val ? this.roleIds : [];
      this.isIndeterminate = false;
    },
    handleCheckedRolesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.rolesOptions.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.rolesOptions.length;
    },
    setRolesOk() {
      if (this.checkedRoles.length > 0) {
        setRoles(this.updateId, this.checkedRoles).then(res => {
          if (res.data.code == 200) {
            this.$message.success("角色设置成功")
            this.dialogVisibleSetRole = false
            this.initTableData();
          }
        })
      } else {
        this.$message.warning("请先选择角色")
      }
    }
  }
}
</script>

<style>
.el-dialog {
  position: absolute;
  top: -40px;
  margin-left: 550px;
}

.avatar-uploader {
  height: 102px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>